import { queryNearbyShopList } from "@src/api/booking";
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from '@src/store/base';
import location from "@src/store/location";
import router from "@src/router";

Component({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }, {
    store: location,
    fields: ['latitude', 'longitude', 'auth'],
    actions: ['getLocation', 'showAuthTip']
  }],
  options: {
    addGlobalClass: true
  },
  data: {
    nearbyShopList: null,
    loading: true,
    showError: null
  },
  lifetimes: {
    ready: function () {
      if (this.data.latitude == null || this.data.longitude === null) {
        this.getLocation().then((res) => {
          this.queryNearbyShopListReq(res.latitude, res.longitude);
        }).catch(error => {
          this.showAuthTip(error);
          this.queryNearbyShopListReq();
        });
      } else {
        this.queryNearbyShopListReq(this.data.latitude, this.data.longitude);
      }
    },
    detached: function () {
    }
  },
  methods: {
    chooseItem(item) {

    },
    queryNearbyShopListReq(latitude, longitude) {
      let data = {};
      if (latitude) {
        data = {
          latitude: latitude,
          longitude: longitude
        }
      }
      this.setData({ loading: true })
      return queryNearbyShopList(data).then(res => {
        this.setData({ loading: false })
        if (res.code === 0) {
          /*数据处理*/
          let list = res.data;
          list.forEach(item => {
            if (item.distance) {
              if (item.distance < 1000) {
                item.distance = item.distance.toFixed(2) + "米"
              } else {
                item.distance = (Math.round(item.distance / 100) / 10).toFixed(1) + "km"
              }
            }
          })
          console.log('list', list)
          this.setData({ 'nearbyShopList': list, showError: list.length === 0 })
        }
      })
    }
  }
})
